
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Cookies from "js-cookie";
import Test from '../views/Test.vue'
import Home from "@/views/Home.vue"
import Layout from "@/views/Layout.vue"
import Login from "@/views/Login.vue"
import About from "@/views/About.vue"
import store from "@/store";
import { message } from "ant-design-vue";

const routes: Array<RouteRecordRaw> = [
  {
    //主页入口
    path: '/',
    component: Layout,
    redirect:"/index",
    children: [
      {
        //主页(所有文章)
        path: '/index',
        component: Home
      },
      {
        //所有文章
        path: '/allArticle',
        component: () => import(/* webpackChunkName: "allArticle" */ "@/views/AllArticle.vue"),
      },
      {
        //文章详情
        path: '/article/detail',
        name: 'ArticleDetail',
        component: () => import(/* webpackChunkName: "articleDetail" */ "@/views/ArticleDetail.vue"),
        
      },
      {
        //个人中心
        path: '/space',
        name: 'space',
        component: () => import(/* webpackChunkName: "space" */ "@/views/Space.vue")
      },
      {
        //关于我
        path: '/aboutMe',
        name: 'aboutMe',
        component: () => import(/* webpackChunkName: "about" */ "@/views/About.vue")
      },
      {
        //文章管理
        path: '/manage',
        name: 'manage',
        component: () => import(/* webpackChunkName: "manage" */ "@/views/Manage.vue")
      },
      {
        //文章管理
        path: '/articleManage',
        name: 'articleManage',
        component: () => import(/* webpackChunkName: "articleManage" */ "@/views/ArticleManage.vue")
      },
      {
        //test
        path: '/test',
        name: 'test',
        component: () => import(/* webpackChunkName: "test" */ "@/views/Test.vue")
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ "@/views/Login.vue")
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

router.beforeEach((to, from, next) => {
  // 基本校验
  if (to.meta.auth) {
    // 需要鉴权的页面，进行前端检查，主要检查cookie中有没有标志位islogined
    // 后端依旧需要对需要鉴权的接口访问做校验，不能依赖前端的判定
    const token = store.getters.token
    if (token === "") {
      message.info("请先登录")
      next("/login")
    } else {
      next()
    }
  } else {
    next();
  }
});

export default router;
